package com.kye.express.business.jd_reservation.edit;

import android.text.TextUtils;

import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.ErrorView;
import com.kye.express.contract.base.view.IView;
import com.kye.express.contract.base.view.LoadingView;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.UserSession;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.jd_reservation.JDWaybillsBean;
import com.kye.model.bean.jd_reservation.request.RequestAddUpdateJD;
import com.kye.model.bean.jd_reservation.request.RequestGetJDWaybill;
import com.kye.model.bean.user.User;
import com.kye.model.gson_adapter.ApiException;
import com.kye.model.service.JDService;

import java.util.Date;
import java.util.List;

import io.reactivex.MaybeObserver;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;

public interface JdReservationEditContract {
    interface JdReservationEditView extends IView, LoadingView, ErrorView {

        void onGetJdWaybill(JDWaybillsBean.JDWaybill jDWaybill);

        void onAddOrUpdateSuccess();
    }

    class JdReservationEditPresenter extends BasePresenter<JdReservationEditView> {

        public void getWaybill(String waybill) {
            UserSession.getInstance()
                    .getUserForRx()
                    .firstOrError()
                    .flatMap(new Function<User, SingleSource<OpenApiResult<JDWaybillsBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<JDWaybillsBean>> apply(User user) throws Exception {
                            return RetrofitManager.getInstance()
                                    .createOpenApiService(JDService.class)
                                    .getJDWaybills(new RequestGetJDWaybill(user.getPhone(), waybill, 1, 1));
                        }
                    })
                    .map(new Function<OpenApiResult<JDWaybillsBean>, List<JDWaybillsBean.JDWaybill>>() {
                        @Override
                        public List<JDWaybillsBean.JDWaybill> apply(OpenApiResult<JDWaybillsBean> jDWaybillBeanOpenApiResult) throws Exception {
                            return jDWaybillBeanOpenApiResult.getData().getDatas();
                        }
                    })
                    .filter(new Predicate<List<JDWaybillsBean.JDWaybill>>() {
                        @Override
                        public boolean test(List<JDWaybillsBean.JDWaybill> jDWaybills) throws Exception {
                            if (jDWaybills.isEmpty()) throw new NullPointerException();

                            return true;
                        }
                    })
                    .map(new Function<List<JDWaybillsBean.JDWaybill>, JDWaybillsBean.JDWaybill>() {
                        @Override
                        public JDWaybillsBean.JDWaybill apply(List<JDWaybillsBean.JDWaybill> jDWaybills) throws Exception {
                            for (JDWaybillsBean.JDWaybill jDWaybill : jDWaybills) {
                                if (!waybill.equals(jDWaybill.getWaybill())) continue;
                                return jDWaybill;
                            }

                            throw new NullPointerException("没有匹配的单号");
                        }
                    })
                    .compose(getView().bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new MaybeObserver<JDWaybillsBean.JDWaybill>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(JDWaybillsBean.JDWaybill jDWaybill) {
                            getView().onLoaded();
                            getView().onGetJdWaybill(jDWaybill);
                        }

                        @Override
                        public void onError(Throwable e) {
                            getView().onLoaded();

                            getView().onGetJdWaybill(null);

                            if (e instanceof ApiException) {
                                getView().onError(((ApiException) e).getOpenApiResult().getMsg());
                            } else if (e instanceof NullPointerException) {
                                getView().onError("该运单不存在或已签收");
                            } else {
                                getView().onError();
                            }
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }

        public void submit(String billId, String orderno, int itemCount, String appointCount, List<?> appointCodes, Date startTime, String goodsCode, List<?> purchaseCodes, Date endTime, String reservationWarehouse) {
            UserSession.getInstance()
                    .getUserForRx()
                    .firstOrError()
                    .flatMap(new Function<User, SingleSource<OpenApiResult<Object>>>() {
                        @Override
                        public SingleSource<OpenApiResult<Object>> apply(User user) throws Exception {
                            String appointCodesString = TextUtils.join(",", appointCodes);
                            if (appointCodesString.endsWith(","))
                                appointCodesString = appointCodesString.substring(0, appointCodesString.length() - 1);

                            String purchaseCodesString = TextUtils.join(",", purchaseCodes);
                            if (purchaseCodesString.endsWith(","))
                                purchaseCodesString = purchaseCodesString.substring(0, purchaseCodesString.length() - 1);

                            return RetrofitManager.getInstance()
                                    .createOpenApiService(JDService.class)
                                    .addUpdateJD(new RequestAddUpdateJD(user.getPhone(), billId == null ? 1 : 2, billId, orderno, itemCount, appointCount, appointCodesString, startTime, goodsCode, purchaseCodesString, endTime, reservationWarehouse));
                        }
                    })
                    .compose(getView().bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<Object>() {
                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<Object> result, Object o) {
                            getView().onAddOrUpdateSuccess();
                        }

                        @Override
                        public void onApiError(OpenApiResult<Object> result, int code, String msg) {
                            getView().onError(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError();
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }
    }
}
